import * as THREE from 'three';
import vertexShader from '@/shader/atmosphere/vertexShader.glsl';
import fragmentShader from '@/shader/atmosphere/fragmentShader.glsl';
import innerVertexShader from '@/shader/atmosphereInner/vertexShader.glsl';
import innerFragmentShader from '@/shader/atmosphereInner/fragmentShader.glsl';

export default class {
  config = {
    height: 50,
    opacity: 0.5,
    color: 'rgb(162,200,248)'
  };
  radius: number;
  outRadius: number;
  mesh = new THREE.Group();
  constructor(radius, color) {
    this.radius = radius;
    this.outRadius = radius + 50;
    this.createOutAtmosphere(radius, color);
    this.createInAtmosphere(radius + this.config.height, color);
  }
  createOutAtmosphere(radius, color) {
    const option = {
      vertexShader,
      fragmentShader,
      transparent: true,
      depthWrite: false,
      blending: THREE.NormalBlending
    };
    console.log(radius);
    const division = Math.sqrt(radius * radius - 1000000) / radius;
    const material1 = new THREE.ShaderMaterial({
      uniforms: {
        division: { value: division },
        coeficient: { value: -0.0001 },
        power: { value: 4 },
        scale: { value: 0.85 },
        glowColor: { value: new THREE.Color(color) },
        opacity: { value: this.config.opacity }
      },
      ...option
    });
    const geometry = new THREE.SphereGeometry(radius, 64, 64);
    this.mesh.add(new THREE.Mesh(geometry, material1));
  }
  createInAtmosphere(radius, color) {
    const option = {
      depthTest: false,
      depthWrite: false,
      transparent: true,
      blending: THREE.NormalBlending,
      vertexShader: innerVertexShader,
      fragmentShader: innerFragmentShader
    };
    const division = Math.sqrt(radius * radius - 1000000) / radius;
    const material = new THREE.ShaderMaterial({
      uniforms: {
        division: { value: division },
        coeficient: { value: 0.0001 },
        power: { value: 0.5 },
        scale: { value: 0.5 },
        glowColor: { value: new THREE.Color(color) },
        opacity: { value: 1 }
      },
      ...option
    });
    console.log(radius);
    const geometry = new THREE.SphereGeometry(radius, 64, 64);
    this.mesh.add(new THREE.Mesh(geometry, material));
  }
  setColor(color) {
    const [body, outer] = this.mesh.children;
    if (body instanceof THREE.Mesh) {
      body.material.uniforms.glowColor.value = new THREE.Color(color);
    }
    if (outer instanceof THREE.Mesh) {
      outer.material.uniforms.glowColor.value = new THREE.Color(color);
    }
  }
}
